<?php
class IMDB_Search_Title extends IMDB_Search {

    const REGEX_YEAR = "#\(([0-9?]{4})\)#i";
	const REGEX_AKA = "#(?:<br>)?aka\s<em>\"([^\"]*)\"</em>(.*?)<br>#i";
	/**
	 * FIXME: REGEX_AKA_INFO, doesn't parse case: " - <em>(something)</em>"
	 **/
    const REGEX_AKA_INFO = "#\s(?:)?(?:\s)?(?:(.*?))?(?:\s)?s(?:<em>\(([^\)]*)\)</em>)?\s?,?#i";
    
    protected function postParse($oResult) {
    	//Clean up Title
		$oResult->sTitle = str_replace("\"", "", $oResult->sLinkText);
		
		//Parse out the year from the brackets
		$sBracket = $oResult->sBracket;
		$aMatches = array();
		preg_match(self::REGEX_YEAR, $sBracket, $aMatches);
		$iYear = (int) $aMatches[1];
        $oResult->iYear = $iYear;
		
		$sAfterBracket = $oResult->sAfterBracket;
        if ($sAfterBracket != "") {
        	$sRemove = chr(160);
			$sAfterBracket = str_replace($sRemove, "", $sAfterBracket);
			$sAfterBracket .= "<br>";
			
            $aMatches = array();
            preg_match_all(self::REGEX_AKA, $sAfterBracket, $aMatches);

			$aAlternateTitles = array();
			foreach ($aMatches[1] as $K => $Title) {
				$aInfoMatches = array();
				$sAKAInfo = $aMatches[2][$K] . " "; //Pad with a space to aid regex
				preg_match_all(self::REGEX_AKA_INFO, $sAKAInfo, $aInfoMatches);
				print_r($aInfoMatches);
				$aAKAInfo = array();
				foreach ($aInfoMatches[0] as $K => $sMatched) {
					$Country = (!empty($aInfoMatches[1][$K]) ? $aInfoMatches[1][$K] : false);
					$Description = (!empty($aInfoMatches[2][$K]) ? $aInfoMatches[2][$K] : false);
					if (!$Country && !$Description)
						continue;
					$aAKAInfo[] = array(
						"Country"		=>	$Country,
						"Description"	=>	$Description);
				}
				
				$aAlternateTitles[] = new IMDB_AKA_Title($Title, $aAKAInfo);
			}
			$oResult->aAlternateTitles = $aAlternateTitles;
        }
		
		//Stick it all into its final result class
		$oResult = new IMDB_Search_Result_Title($oResult);
		return $oResult;
    }
}
?>